package com.peas.platform.module.icims.expenditure.kpis.domain.impl;

import cn.hutool.core.util.StrUtil;
import com.peas.platform.framework.mybatisplus.domain.BaseDomainImpl;
import com.peas.platform.framework.mybatisplus.repository.BaseRepository;
import com.peas.platform.module.icims.base.sys.enums.CommonYesNo;
import com.peas.platform.module.icims.base.sys.service.SequenceService;
import com.peas.platform.module.icims.expenditure.kpis.adapter.repository.ExpenditureQuotaRepository;
import com.peas.platform.module.icims.expenditure.kpis.adapter.repository.po.ExpenditureQuotaPo;
import com.peas.platform.module.icims.expenditure.kpis.domain.ExpenditureQuotaDomain;
import com.peas.platform.module.icims.expenditure.kpis.dto.ExpenditureKpiDto;
import com.peas.platform.module.icims.expenditure.kpis.dto.ExpenditureQuotaDto;
import com.peas.platform.module.icims.expenditure.kpis.service.ExpenditureKpiService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Component
public class ExpenditureQuotaDomainImpl extends BaseDomainImpl<ExpenditureQuotaDto, ExpenditureQuotaPo> implements ExpenditureQuotaDomain {

    @Resource
    private ExpenditureQuotaRepository expenditureQuotaRepository;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private ExpenditureKpiService expenditureKpiService;

    @Override
    public BaseRepository<ExpenditureQuotaPo> getMapper() {
        return expenditureQuotaRepository;
    }

    @Override
    public Class<? extends BaseRepository<ExpenditureQuotaPo>> getRepositoryClass() {
        return ExpenditureQuotaRepository.class;
    }

    @Transactional
    @Override
    public int save(ExpenditureQuotaDto dto) {
        if (StrUtil.isBlank(dto.getQuotaCode())) {
            String code = sequenceService.genSequence("expenditure", "ExpenditureQuotaDto", "EQDD", 4, 1);
            dto.setQuotaCode(code);
        }
        int result = super.save(dto);
        this.checkRepetition("quotaCode", dto.getQuotaCode());
        //回写指标单
        ExpenditureKpiDto kpi = expenditureKpiService.getById(dto.getExpenditureKpiId());
        if (!StrUtil.equals(CommonYesNo.yes.getKey(), kpi.getIsBegin())) {
            kpi.setIsBegin(CommonYesNo.yes.getKey());
            expenditureKpiService.updateById(kpi);
        }
        return result;
    }

    @Transactional
    @Override
    public int updateById(ExpenditureQuotaDto dto) {
        int result = super.updateById(dto);
        this.checkRepetition("quotaCode", dto.getQuotaCode());
        //回写指标单
        ExpenditureKpiDto kpi = expenditureKpiService.getById(dto.getExpenditureKpiId());
        if (!StrUtil.equals(CommonYesNo.yes.getKey(), kpi.getIsBegin())) {
            kpi.setIsBegin(CommonYesNo.yes.getKey());
            expenditureKpiService.updateById(kpi);
        }
        return result;
    }

}
